package com.ccb.sc.common.conf;

import com.aliyun.oss.OSSClient;
import com.ccb.sc.common.util.oss.OssClientFactory;
import com.ccb.sc.common.util.oss.OssManager;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ken
 * @version 1.0
 * @date 2020-09-22
 */
@Configuration
@EnableConfigurationProperties({OssProperties.class})
public class OssConfig {

    private final OssProperties ossProperties;

    public OssConfig(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }

    @Bean
    public OssManager createOssManager(OSSClient ossClient) {
        Map<String,String> buckets = new HashMap<>();
        String url = "https://";
        if (StringUtils.hasText(this.ossProperties.getCdnHost())) {
            url += this.ossProperties.getCdnHost();
        }else {
            url += this.ossProperties.getBucket() + "."+ this.ossProperties.getEndpoint();
        }
        buckets.put(this.ossProperties.getBucket(), url);
        return new OssManager(ossClient, buckets);
    }

    @Bean
    public OSSClient createOssClient(){
        return OssClientFactory.getOSSClient(this.ossProperties.getEndpoint(),
                this.ossProperties.getAccessKeyId(),
                this.ossProperties.getAccessKeySecret());
    }
}
